<template>
	<view class="container">
		<view class="appointment-list">
			<view class="appointment-item" v-for="(appointment, index) in appointmentList" :key="index">
				<view class="appointment-time">
					<text class="time-label">{{ formatDate(appointment.appointDate) }}</text>
				</view>
				<view class="appointment-details">
					<view class="appointment-info">
						<text class="info-label">预约编号:</text>
						<text class="info-content">{{ appointment.appointCode }}</text>
					</view>
					<view class="appointment-info">
						<text class="info-label">预约人:</text>
						<text class="info-content">{{ appointment.clientName }}</text>
					</view>
					<view class="appointment-info">
						<text class="info-label">预约医生:</text>
						<text class="info-content">{{ appointment.doctorName }}</text>
					</view>
					<view class="appointment-info">
						<text class="info-label">备注信息:</text>
						<text class="info-content">{{ appointment.remarks || '无' }}</text>
					</view>
				</view>
				<view class="appointment-status">
					<text
						:class="getStatusClass(appointment.appointStatus)">{{ appointStatusMenu(appointment.appointStatus) }}</text>
				</view>



				<view class="appointment-action">
					<!-- <uv-modal ref="modal" content='确定要取消所选预约？' :asyncClose="true" @confirm="confirmCancel"
						showCancelButton=true></uv-modal> -->
					<uv-button v-if="appointment.appointStatus === 0 || appointment.appointStatus === 1"
						class="cancel-btn" type="danger" size="mini" @click="confirmCancel(appointment.id)">
						取消预约
					</uv-button>
					
					<uv-button v-if="appointment.appointStatus === 1"
						class="cancel-btn" type="success" size="mini" @click="finishCancel(appointment.id)">
						完成预约
					</uv-button>
				</view>
			</view>

			<!-- 分页控件 -->
			<view class="pagination">
				<button class="page-btn" @click="prevPage" :disabled="queryParams.pageNo === 1">
					上一页
				</button>
				<text class="page-info">
					第 {{ queryParams.pageNo }} 页，共 {{ totalPages }} 页
				</text>
				<button class="page-btn" @click="nextPage" :disabled="queryParams.pageNo === totalPages">
					下一页
				</button>
			</view>
		</view>

	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		computed,
		onMounted
	} from 'vue';

	// 格式化时间戳为可读的日期格式
	const formatDate = (timestamp) => {
		if (!timestamp) return '';
		const date = new Date(timestamp);
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		const hours = String(date.getHours()).padStart(2, '0');
		const minutes = String(date.getMinutes()).padStart(2, '0');
		return `${year}-${month}-${day} ${hours}:${minutes}`;
	};

	// 预约状态数组
	const appointStatusMenu = (appointStatus) => {
		if (appointStatus === 0) {
			return "未处理";
		} else if (appointStatus === 1) {
			return "已确认";
		} else if (appointStatus === 2) {
			return "已完成";
		} else if (appointStatus === -1) {
			return "已取消";
		}
		return "未知状态";
	};

	// 获取状态对应的样式类
	const getStatusClass = (status) => {
		return `status-text status-${status}`;
	};

	// 预约列表数据
	const appointmentList = reactive([]);

	// 查询参数
	const queryParams = reactive({
		pageNo: 1,
		pageSize: 5,
		clientCode: '',
		clientName: ''
	});

	// 总页数
	const totalPages = ref(1);




	


	// const modal = ref(null); // 确保 modal 是一个 ref
	
	// const openModal = (id) => {
	//   currentAppointment.id = id;
	//     modal.value.open();
	// };
	
	// 存储所选预约数据
	const currentAppointment = reactive({
		id: undefined
	});
	
	// 确认完成预约
	const finishCancel = (id) => {
		console.log(id)
		if (!id) return;
	
		// 调用完成预约接口
		uni.request({
			url: 'http://localhost:58080/admin-api/base/appoint-data/finish', // 完成预约接口地址
			method: 'GET',
			data: {
				id: id
			},
			header: {
				'Content-Type': 'application/json',
				// 如果需要携带 token，可以从本地存储中获取并设置到请求头中
				'Authorization': `Bearer ${uni.getStorageSync('userInfo').accessToken}`
			},
			success: (res) => {
				if (res.data.code === 0) {
					// 完成预约成功
					uni.showToast({
						title: '完成预约成功',
						icon: 'success'
					});
					// 更新预约状态为已取消
					// 需要在这里找到对应的appointment并更新其状态
					const index = appointmentList.findIndex(item => item.id === currentAppointment.id);
					if (index !== -1) {
						appointmentList[index].appointStatus = -1;
					}
					// 刷新预约列表
					getMyAppointList();
					// 关闭弹框
					closeCancelModal();
				} else {
					// 完成预约失败
					uni.showToast({
						title: res.data.msg || '完成预约失败',
						icon: 'none'
					});
				}
			},
			fail: (err) => {
				// 请求失败
				uni.showToast({
					title: '网络请求失败',
					icon: 'none'
				});
				console.error(err);
			}
		});
	};
	
	

	// 确认取消预约
	const confirmCancel = (id) => {
		console.log(id)
		if (!id) return;

		// 调用取消预约接口
		uni.request({
			url: 'http://localhost:58080/admin-api/base/appoint-data/cancel', // 取消预约接口地址
			method: 'GET',
			data: {
				id: id
			},
			header: {
				'Content-Type': 'application/json',
				// 如果需要携带 token，可以从本地存储中获取并设置到请求头中
				'Authorization': `Bearer ${uni.getStorageSync('userInfo').accessToken}`
			},
			success: (res) => {
				if (res.data.code === 0) {
					// 取消预约成功
					uni.showToast({
						title: '取消预约成功',
						icon: 'success'
					});
					// 更新预约状态为已取消
					// 需要在这里找到对应的appointment并更新其状态
					const index = appointmentList.findIndex(item => item.id === currentAppointment.id);
					if (index !== -1) {
						appointmentList[index].appointStatus = -1;
					}
					// 刷新预约列表
					getMyAppointList();
					// 关闭弹框
					closeCancelModal();
				} else {
					// 取消预约失败
					uni.showToast({
						title: res.data.msg || '取消预约失败',
						icon: 'none'
					});
				}
			},
			fail: (err) => {
				// 请求失败
				uni.showToast({
					title: '网络请求失败',
					icon: 'none'
				});
				console.error(err);
			}
		});
	};






	// 获取我的预约列表
	const getMyAppointList = () => {
		uni.request({
			url: 'http://localhost:58080/admin-api/base/appoint-data/page',
			method: 'GET',
			data: {
				pageNo: queryParams.pageNo,
				pageSize: queryParams.pageSize,
				clientCode: queryParams.clientCode,
				clientName: queryParams.clientName
			},
			header: {
				'Content-Type': 'application/json',
				// 如果需要携带 token，可以从本地存储中获取并设置到请求头中
				'Authorization': `Bearer ${uni.getStorageSync('userInfo').accessToken}`
			},
			success: (res) => {
				if (res.data.code === 0) {
					const response = res.data;
					if (response.code === 0) {
						appointmentList.splice(0, appointmentList.length, ...response.data.list);
						totalPages.value = Math.ceil(response.data.total / queryParams.pageSize);
					} else {
						uni.showToast({
							title: response.msg || '获取预约列表失败',
							icon: 'none'
						});
					}
				} else {
					uni.showToast({
						title: '获取预约列表失败',
						icon: 'none'
					});
				}
			},
			fail: (err) => {
				uni.showToast({
					title: '网络请求失败',
					icon: 'none'
				});
				console.error(err);
			}
		});
	};

	// 处理页码变更
	const prevPage = () => {
		if (queryParams.pageNo > 1) {
			queryParams.pageNo--;
			getMyAppointList();
		}
	};

	const nextPage = () => {
		if (queryParams.pageNo < totalPages.value) {
			queryParams.pageNo++;
			getMyAppointList();
		}
	};

	// 页面加载时初始化
	onMounted(() => {
		getUserProfile();
	});

	// 获取用户信息
	const getUserProfile = () => {
		uni.request({
			url: 'http://localhost:58080/admin-api/system/user/profile/get', // 获取用户信息接口地址
			method: 'GET',
			header: {
				'Content-Type': 'application/json',
				// 如果需要携带 token，可以从本地存储中获取并设置到请求头中
				'Authorization': `Bearer ${uni.getStorageSync('userInfo').accessToken}`
			},
			success: (res) => {
				if (res.data.code === 0) {
					// 赋值查询参数中的个人信息
					const profileData = res.data.data;
					queryParams.clientCode = profileData.username;
					queryParams.clientName = profileData.nickname;
					getMyAppointList();
				} else {
					// 获取用户信息失败
					uni.showToast({
						title: res.data.msg || '获取用户信息失败',
						icon: 'none'
					});
				}
			},
			fail: (err) => {
				// 请求失败
				uni.showToast({
					title: '网络请求失败',
					icon: 'none'
				});
				console.error(err);
			}
		});
	};
</script>

<style scoped>
	.container {
		padding: 20px;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.appointment-list {
		background-color: #fff;
		border-radius: 10px;
		padding: 15px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
	}

	.appointment-item {
		display: flex;
		flex-direction: column;
		padding: 15px 0;
		border-bottom: 1px solid #f0f0f0;
		position: relative;
	}

	.appointment-time {
		margin-bottom: 10px;
	}

	.time-label {
		font-size: 16px;
		font-weight: bold;
		color: #333;
	}

	.appointment-details {
		display: flex;
		flex-direction: column;
		margin-bottom: 10px;
	}

	.appointment-info {
		display: flex;
		margin-bottom: 5px;
	}

	.info-label {
		font-weight: bold;
		color: #666;
		margin-right: 5px;
	}

	.info-content {
		flex: 1;
		color: #333;
	}

	.appointment-status {
		position: absolute;
		top: 0;
		right: 0;
		background-color: #f0f0f0;
		padding: 5px 10px;
		border-radius: 0 10px 0 10px;
		font-size: 12px;
	}

	.status-text {
		color: #333;
	}

	.status-0 {
		color: #999;
	}

	.status-1 {
		color: #1aad19;
	}

	.status-2 {
		color: #ff9900;
	}

	.status--1 {
		color: #ff3b30;
	}

	.appointment-action {
		display: flex;
		justify-content: flex-end;
	}

	.cancel-btn {
		width: 120px;
	}

	/* 分页样式 */
	.pagination {
		margin-top: 20px;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.page-btn {
		width: 80px;
		height: 30px;
		margin: 0 10px;
		background-color: #f5f5f5;
		border: 1px solid #ddd;
		border-radius: 5px;
		font-size: 14px;
	}

	.page-info {
		font-size: 14px;
		color: #666;
	}
</style>